package pers.liuchengyin.enums;

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @ClassName ErrorCode
 * @Description
 * @Author 柳成荫
 * @Date 2022/3/27
 */
public enum ErrorCode {
    /** 通用错误码 */
    SYSTEM_ERROR_NET(101, "抱歉，网络开小差了，请稍后重试！"),
    PARAM_ERROR(102, "参数错误"),
    ;

    /**
     * 根据code获取对应的枚举 - v1(优先使用这个)
     */
    public static Map<Integer, ErrorCode> code2EnumMap;

    static {
        code2EnumMap = Stream.of(ErrorCode.values()).collect(Collectors.toMap(
                ErrorCode::getCode,
                Function.identity()
        ));
    }

    private int code;
    private String msg;

    ErrorCode(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    /**
     * 替换ErrorCode的msg
     * @param errorCode ErrorCode
     * @param msg 要替换的文本
     * @return errorCode
     */
    public static ErrorCode replaceMsg(ErrorCode errorCode, String msg) {
        errorCode.msg = msg;
        return errorCode;
    }

    /**
     * 根据code获取对应的枚举 - v2
     * @param code code
     * @return errorCode
     */
    public static ErrorCode getTypeByCode(int code) {
        for (ErrorCode value : ErrorCode.values()) {
            if (value.code == code) {
                return value;
            }
        }
        return null;
    }

    /**
     * 根据枚举名获取对应的枚举
     * @param name 枚举名
     * @return errorCode
     */
    public static ErrorCode getTypeByName(String name) {
        for (ErrorCode value : ErrorCode.values()) {
            if (value.name().equals(name)) {
                return value;
            }
        }
        return null;
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

}